Here the length is declared before the for loop and the function is giving the correct answer.
The console: []
function dropElements(arr, func) {
let len = arr.length;
for (let i = 0; i < len; i++) {
if (!func(arr[0])) {
arr.shift();
}
}
return arr;
}
console.log(dropElements([1, 2, 3, 4], function(n) {
return n > 5;
}));
Now the length is used directy in the for loop and the function is leaving behind two elements of the array. The console: [3,4]
function dropElements(arr, func) {
for (let i = 0; i < arr.length; i++) {
if (!func(arr[0])) {
arr.shift();
}
}
return arr;
}
console.log(dropElements([1, 2, 3, 4], function(n) {
return n > 5;
}));